<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.workFlow.flowTemplateProperty')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="600"
      :width="600"
    >
      <Tabs v-model:activeKey="activeKey">
        <TabPane key="BasicAttribute" :tab="t('routes.demo.workFlow.BasicAttribute')">
          <BasicForm @register="registerForm" size="small" />
        </TabPane>
        <TabPane key="overdueSetting" :tab="t('routes.demo.workFlow.overdueSetting')">
          <Form :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" :model="overdueForm">
            <FormItem :label="t('routes.demo.workFlow.handleWay')">
              <Select v-model:value="overdueForm.handleWay">
                <SelectOption value="1">{{ t('routes.demo.workFlow.way1') }}</SelectOption>
                <SelectOption value="2">{{ t('routes.demo.workFlow.way2') }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem :label="t('routes.demo.workFlow.overdueTime')">
              <Row align="middle" gutter="10">
                <Col :span="8">
                  <Input
                    v-model:value="overdueForm.day"
                    :placeholder="t('routes.demo.workFlow.dayPlaceholder')"
                    :disabled="overdueForm.handleWay == '2'"
                  /> </Col
                ><span>{{ t('routes.demo.workFlow.day') }}</span>
                <Col :span="8">
                  <Input
                    v-model:value="overdueForm.hour"
                    :placeholder="t('routes.demo.workFlow.hourPlaceholder')"
                    :disabled="overdueForm.handleWay == '2'"
                  /> </Col
                ><span>{{ t('routes.demo.workFlow.hour') }}</span>
              </Row>
            </FormItem>
          </Form>
        </TabPane>
        <TabPane key="messageSetting" :tab="t('routes.demo.workFlow.messageSetting')">
          <Form :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" :model="messageForm">
            <FormItem :label="t('routes.demo.workFlow.overdueMessage')">
              <RadioGroup v-model:value="messageForm.overdueMessage">
                <Radio value="1">{{ t('common.yes') }}</Radio>
                <Radio value="2">{{ t('common.no') }}</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem :label="t('routes.demo.workFlow.handleWay')">
              <Select
                v-model:value="messageForm.handleWay"
                :disabled="messageForm.overdueMessage == '2'"
              >
                <SelectOption value="1">{{ t('routes.demo.workFlow.way3') }}</SelectOption>
                <SelectOption value="2">{{ t('routes.demo.workFlow.way4') }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem :label="t('routes.demo.workFlow.receiver')">
              <Select
                v-model:value="messageForm.receiver"
                :disabled="messageForm.overdueMessage == '2'"
              >
                <SelectOption v-for="item in receiverList" :key="item.id" :value="item.id">{{
                  item.name
                }}</SelectOption>
              </Select>
            </FormItem>
          </Form>
        </TabPane>
      </Tabs>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import {
    Tabs,
    TabPane,
    Form,
    FormItem,
    Select,
    SelectOption,
    Input,
    Row,
    Col,
    RadioGroup,
    Radio,
  } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getCreateFlowTemplate } from './flowData';
  import { getFlowTemplateApi } from '/@/api/demo/flow';
  import { Getallpersondto } from '/@/api/demo/system';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { useRouter } from 'vue-router';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();

  const isUpdate = ref(true);
  const activeKey = ref('BasicAttribute');
  // 超期设定
  const overdueForm = ref<any>({
    handleWay: '2', // 1:在建立工作流实例时允许修改超期时间 2:在建立工作流实例时不允许修改超期时间
    day: '',
    hour: '',
  });
  // 消息设定
  const messageForm = ref<any>({
    overdueMessage: '2', // 1是 2否
    handleWay: '2', // 1:在建立工作流实例时允许修改消息接收人 2:在建立工作流实例时不允许修改消息接收人
    receiver: '', // 消息接收人,如果有多个，用户id之间用逗号隔开
  });
  const receiverList = ref<any>([]);
  // 流程
  const webList: any = ref([]);
  const listStep: any = ref([]);
  const form: any = ref(null);
  const useCommonStore = useUserStore();
  const router = useRouter();

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    const peopleList = await Getallpersondto('');
    receiverList.value = peopleList;
    // 重置表单
    webList.value = [];
    listStep.value = [];
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      const res = await getFlowTemplateApi(data.record.id);
      const mainwfdto = res.mainwfdto;
      webList.value = res.weblist;
      listStep.value = res.liststep;
      mainwfdto['bzxzselected'] = res.mainwfdto.bzxzselected === '1';
      mainwfdto['htfsselected'] = res.mainwfdto.htfsselected === '1';
      mainwfdto['classApplicable'] =
        res.mainwfdto.classApplicable.length === 0 ? null : res.mainwfdto.classApplicable;
      setFieldsValue({ ...mainwfdto });
      overdueForm.value = res.mainwfdto.overDueForm;
      messageForm.value = res.mainwfdto.messageForm;
    }
  });

  // 基本属性
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    schemas: getCreateFlowTemplate(isUpdate),
    showActionButtonGroup: false,
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      // 初始化表单值
      const {
        bzxzselected,
        htfsselected,
        remark,
        actor,
        classApplicable,
        bzxz,
        htfs,
        type,
        signature,
        ...restValues
      } = values;

      form.value = {
        ...restValues,
        creator: useCommonStore.userInfo?.userId,
        bzxzselected: bzxzselected ? '1' : '0',
        htfsselected: htfsselected ? '1' : '0',
        signature: signature ? '1' : '0',
        remark: remark || '',
        actor: actor || 'sa',
        classApplicable: classApplicable ?? null,
        bzxz: bzxz || '1',
        htfs: htfs || '1',
        type: type || '通知流程',
        overDueForm: overdueForm.value,
        messageForm: messageForm.value,
      };

      const formStr = JSON.stringify(form.value);
      const webListStr = JSON.stringify(webList.value);
      const listStepStr = JSON.stringify(listStep.value);

      router.push({
        name: '流程模型',
        params: { form: formStr, weblist: webListStr, liststep: listStepStr },
      });

      emit('success');
      createMessage.success('成功');
      handleCancel();
    } catch (error) {
      console.error('Error in handleSubmit:', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 取消
  function handleCancel() {
    activeKey.value = 'BasicAttribute';
    overdueForm.value.handleWay = '2';
    overdueForm.value.day = '';
    overdueForm.value.hour = '';
    messageForm.value.overdueMessage = '2';
    messageForm.value.handleWay = '2';
    messageForm.value.receiver = '';
    closeModal();
  }
</script>

<style lang="less" scoped>
  ::v-deep(.rc-virtual-list-scrollbar-thumb) {
    visibility: hidden !important;
  }
</style>
